import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:fishing/models/appointment.dart';
import 'package:fishing/models/order.dart';
import 'package:fishing/services/home_service.dart';
import 'package:fishing/services/order_service.dart';
import 'package:fishing/widgets/message_overlay.dart';
import 'package:fishing/utils/storage_util.dart';
import 'package:go_router/go_router.dart';

class PrebookPage extends StatefulWidget {
  const PrebookPage({super.key});

  @override
  State<PrebookPage> createState() => _PrebookPageState();
}

class _PrebookPageState extends State<PrebookPage> with TickerProviderStateMixin {
  final HomeService _homeService = HomeService();
  final OrderService _orderService = OrderService();
  final Color primaryBlue = const Color(0xFF2196F3);
  
  late TabController _tabController;
  
  // 预约相关
  List<Appointment> _appointments = [];
  bool _isLoadingAppointments = true;
  
  // 订单相关
  List<Order> _orders = [];
  bool _isLoadingOrders = false;
  
  bool _isRefreshing = false;
  final Set<int> _checkingInSegments = <int>{}; // 正在签到的时间段ID集合

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(_onTabChanged);
    _loadAppointments(); // 只加载预约数据
  }

  // Tab切换监听
  void _onTabChanged() {
    print('Tab切换到: ${_tabController.index}');
    print('订单数据为空: ${_orders.isEmpty}');
    print('是否正在加载: $_isLoadingOrders');
    if (_tabController.index == 1 && _orders.isEmpty && !_isLoadingOrders) {
      print('开始加载订单数据...');
      // 切换到订单Tab且订单数据为空时，才加载订单数据
      _loadOrders();
    } else {
      print('不满足加载条件');
    }
  }

  @override
  void dispose() {
    _tabController.removeListener(_onTabChanged);
    _tabController.dispose();
    super.dispose();
  }

  // 加载所有数据（用于刷新）
  Future<void> _loadData() async {
    if (_tabController.index == 0) {
      // 当前在预约Tab，只刷新预约数据
      await _loadAppointments();
    } else {
      // 当前在订单Tab，只刷新订单数据
      await _loadOrders();
    }
  }

  // 加载预约列表
  Future<void> _loadAppointments() async {
    setState(() {
      _isLoadingAppointments = true;
    });

    try {
      final appointments = await _homeService.getUserAppointments();
      setState(() {
        _appointments = appointments;
      });
    } catch (e) {
      MessageOverlay.show(context, message: '加载预约列表失败：$e', type: MessageType.error);
    } finally {
      setState(() {
        _isLoadingAppointments = false;
      });
    }
  }

  // 加载订单列表
  Future<void> _loadOrders() async {
    print('_loadOrders 方法被调用');
    setState(() {
      _isLoadingOrders = true;
    });

    try {
      final userInfoJson = await StorageUtil.getUserInfo();
      print('获取到的用户信息: $userInfoJson');
      
      String? userId;
      if (userInfoJson != null && userInfoJson.isNotEmpty) {
        final userInfo = jsonDecode(userInfoJson);
        userId = userInfo['userId']?.toString();
      }
      
      print('解析出的userId: $userId');
      if (userId != null && userId.isNotEmpty) {
        print('开始调用订单接口...');
        final response = await _orderService.getUserOrders(
          pageNum: 1,
          pageSize: 20,
          userId: userId,
        );
        print('订单接口返回数据: ${response.rows.length} 条订单');
        setState(() {
          _orders = response.rows;
        });
      } else {
        print('userId为空，无法调用订单接口');
      }
    } catch (e) {
      print('加载订单失败: $e');
      MessageOverlay.show(context, message: '加载订单列表失败：$e', type: MessageType.error);
    } finally {
      setState(() {
        _isLoadingOrders = false;
      });
    }
  }

  // 刷新当前Tab数据
  Future<void> _refreshData() async {
    setState(() {
      _isRefreshing = true;
    });

    try {
      await _loadData(); // 根据当前Tab刷新对应数据
    } catch (e) {
      MessageOverlay.show(context, message: '刷新失败：$e', type: MessageType.error);
    } finally {
      setState(() {
        _isRefreshing = false;
      });
    }
  }

  // 取消预约
  Future<void> _cancelAppointment(Appointment appointment) async {
    // 显示确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认取消'),
          content: Text('确定要取消在${appointment.deptName}的预约吗？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              style: TextButton.styleFrom(foregroundColor: Colors.red),
              child: const Text('确认取消'),
            ),
          ],
        );
      },
    );

    if (confirmed == true) {
      try {
        final success = await _homeService.cancelAppointment(appointment.id);
        if (success) {
          MessageOverlay.show(context, message: '预约已取消', type: MessageType.success);
          _loadAppointments(); // 刷新列表
        } else {
          MessageOverlay.show(context, message: '取消预约失败', type: MessageType.error);
        }
      } catch (e) {
        MessageOverlay.show(context, message: '取消预约失败：$e', type: MessageType.error);
      }
    }
  }

  // 签到
  Future<void> _checkinTimeSegment(int timeSegmentId) async {
    // 显示确认对话框
    final bool? confirmed = await showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认签到'),
          content: const Text('确定要签到这个时间段吗？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: const Text('确定签到'),
            ),
          ],
        );
      },
    );

    if (confirmed == true) {
      setState(() {
        _checkingInSegments.add(timeSegmentId);
      });

      try {
        final success = await _homeService.checkinTimeSegment(timeSegmentId);
        if (success) {
          MessageOverlay.show(context, message: '签到成功！', type: MessageType.success);
          _loadAppointments(); // 刷新列表
        } else {
          MessageOverlay.show(context, message: '签到失败，请稍后重试', type: MessageType.error);
        }
      } catch (e) {
        MessageOverlay.show(context, message: '签到失败：$e', type: MessageType.error);
      } finally {
        setState(() {
          _checkingInSegments.remove(timeSegmentId);
        });
      }
    }
  }


  // 格式化时间段
  String _formatTimeRange(String startTime, String endTime) {
    try {
      final start = startTime.substring(0, 5); // HH:mm
      final end = endTime.substring(0, 5); // HH:mm
      return '$start - $end';
    } catch (e) {
      return '$startTime - $endTime';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true,
      backgroundColor: Colors.white,
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () => context.pop(),
        ),
        title: const Text('我的预约&订单'),
        centerTitle: true,
        backgroundColor: primaryBlue,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            onPressed: _isRefreshing ? null : _refreshData,
            icon: _isRefreshing 
                ? const SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    ),
                  )
                : const Icon(Icons.refresh),
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.white70,
          indicatorColor: Colors.white,
          tabs: const [
            Tab(text: '我的预约'),
            Tab(text: '我的订单'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildAppointmentTab(),
          _buildOrderTab(),
        ],
      ),
    );
  }

  // 构建预约Tab
  Widget _buildAppointmentTab() {
    if (_isLoadingAppointments) {
      return const Center(child: CircularProgressIndicator());
    }
    
    if (_appointments.isEmpty) {
      return _buildEmptyState('预约', '暂无预约记录', '快去预约您喜欢的钓位吧！', () => context.go('/fishing'));
    }
    
    return RefreshIndicator(
      onRefresh: _loadAppointments,
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _appointments.length,
        itemBuilder: (context, index) {
          final appointment = _appointments[index];
          return _buildAppointmentCard(appointment);
        },
      ),
    );
  }

  // 构建订单Tab
  Widget _buildOrderTab() {
    if (_isLoadingOrders) {
      return const Center(child: CircularProgressIndicator());
    }
    
    if (_orders.isEmpty) {
      return _buildEmptyState('订单', '暂无订单记录', '快去下单体验钓鱼乐趣吧！', () => context.go('/fishing'));
    }
    
    return RefreshIndicator(
      onRefresh: _loadOrders,
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _orders.length,
        itemBuilder: (context, index) {
          final order = _orders[index];
          return _buildOrderCard(order);
        },
      ),
    );
  }

  // 构建空状态
  Widget _buildEmptyState(String type, String title, String subtitle, VoidCallback onPressed) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.event_busy,
            size: 80,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            title,
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 8),
          Text(
            subtitle,
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: onPressed,
            style: ElevatedButton.styleFrom(
              backgroundColor: primaryBlue,
              padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 12),
            ),
            child: Text(
              '去$type',
              style: const TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  // 构建预约卡片
  Widget _buildAppointmentCard(Appointment appointment) {
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 头部：钓场名称和状态
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Text(
                    appointment.deptName,
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: appointment.statusColor.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: appointment.statusColor),
                  ),
                  child: Text(
                    appointment.statusText,
                    style: TextStyle(
                      fontSize: 12,
                      color: appointment.statusColor,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            
            // 鱼塘信息
            Row(
              children: [
                Icon(Icons.water, size: 16, color: Colors.blue[600]),
                const SizedBox(width: 4),
                Text(
                  appointment.pondName,
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[700],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            
            // 预约人信息
            Row(
              children: [
                Icon(Icons.person, size: 16, color: Colors.grey[600]),
                const SizedBox(width: 4),
                Text(
                  appointment.nickName,
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[700],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            
            // 时间段列表
            ...appointment.timeSegments.map((segment) => _buildTimeSegmentItem(segment)).toList(),
            
            // 操作按钮
            if (appointment.status == 0 || appointment.status == 1|| appointment.status == 5) ...[
              const SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  if (appointment.status == 0) // 待确认状态可以取消
                    TextButton(
                      onPressed: () => _cancelAppointment(appointment),
                      style: TextButton.styleFrom(
                        foregroundColor: Colors.red,
                      ),
                      child: const Text('取消预约'),
                    ),
                ],
              ),
            ],
          ],
        ),
      ),
    );
  }

  // 构建时间段项目
  Widget _buildTimeSegmentItem(TimeSegment segment) {
    final bool isCheckedIn = (segment.checkinStatus ?? segment.status ?? 0) == 1 || (segment.checkinStatus ?? segment.status ?? 0) == 5;
    final bool isCheckingIn = _checkingInSegments.contains(segment.id);
    
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: isCheckedIn ? Colors.green[50] : Colors.blue[50],
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: isCheckedIn ? Colors.green[200]! : Colors.blue[200]!),
      ),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
            decoration: BoxDecoration(
              color: isCheckedIn ? Colors.green : primaryBlue,
              borderRadius: BorderRadius.circular(4),
            ),
            child: Text(
              '钓位${segment.seatCode}',
              style: const TextStyle(
                fontSize: 12,
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      segment.appointmentDate,
                      style: const TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    const SizedBox(width: 8),
                    // 签到状态标签
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                      decoration: BoxDecoration(
                        color: segment.checkinStatusColor,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Text(
                        segment.checkinStatusText,
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 10,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 2),
                Text(
                  _formatTimeRange(segment.startTime, segment.endTime),
                  style: TextStyle(
                    fontSize: 13,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
          
          // 签到按钮
          if (!isCheckedIn) ...[
            const SizedBox(width: 8),
            SizedBox(
              height: 32,
              child: ElevatedButton(
                onPressed: isCheckingIn ? null : () => _checkinTimeSegment(segment.id),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.green,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16),
                  ),
                ),
                child: isCheckingIn
                    ? const SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      )
                    : const Text(
                        '签到',
                        style: TextStyle(fontSize: 12),
                      ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  // 构建订单卡片
  Widget _buildOrderCard(Order order) {
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 头部：订单号和状态
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Text(
                    '订单号：${order.orderNo}',
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: _getOrderStatusColor(order.status).withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: _getOrderStatusColor(order.status)),
                  ),
                  child: Text(
                    order.statusDesc,
                    style: TextStyle(
                      fontSize: 12,
                      color: _getOrderStatusColor(order.status),
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            
            // 钓场和鱼塘信息
            Row(
              children: [
                Icon(Icons.business, size: 16, color: Colors.blue[600]),
                const SizedBox(width: 4),
                Text(
                  order.deptName,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(width: 12),
                Icon(Icons.water, size: 16, color: Colors.blue[600]),
                const SizedBox(width: 4),
                Text(
                  order.pondName,
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[700],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            
            // 钓位和时间信息
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                  decoration: BoxDecoration(
                    color: primaryBlue,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    '钓位${order.seatCode}',
                    style: const TextStyle(
                      fontSize: 12,
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Icon(Icons.access_time, size: 16, color: Colors.grey[600]),
                const SizedBox(width: 4),
                Expanded(
                  child: Text(
                    order.startTime,
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[700],
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            
            // 订单类型
            Row(
              children: [
                Icon(Icons.category, size: 16, color: Colors.grey[600]),
                const SizedBox(width: 4),
                Text(
                  order.orderTypeDesc,
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[700],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            
            // 订单项目列表
            if (order.orderItems.isNotEmpty) ...[
              const Text(
                '订单明细：',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                ),
              ),
              const SizedBox(height: 8),
              ...order.orderItems.map((item) => _buildOrderItemRow(item)).toList(),
              const SizedBox(height: 12),
            ],
            
            // 总金额
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '创建时间：${order.createTime}',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
                Text(
                  '总金额：¥${order.totalAmount.toStringAsFixed(2)}',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.red[600],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 构建订单项目行
  Widget _buildOrderItemRow(OrderItem item) {
    return Container(
      margin: const EdgeInsets.only(bottom: 4),
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(6),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            item.itemName,
            style: const TextStyle(fontSize: 13),
          ),
          Text(
            '¥${item.amount.toStringAsFixed(2)}',
            style: const TextStyle(
              fontSize: 13,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  // 获取订单状态颜色
  Color _getOrderStatusColor(int status) {
    switch (status) {
      case 0:
        return Colors.orange; // 未完成
      case 1:
        return Colors.green; // 已完成
      case 2:
        return Colors.red; // 已取消
      default:
        return Colors.grey;
    }
  }
}
